﻿using Sunny.UI;
using System.Collections.Generic;
using CoreShop.Model;
using CoreShop.Services;
using System;
using CoreShop.Model.UI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections;
using System.Security.Policy;
using SqlSugar.Extensions;
using Sunny.UI.Win32;
using System.Windows.Forms;
using System.ComponentModel;
using CoreShop.Library;
using System.Data;
using FastMember;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using Loading;
using CoreShop.App.Units.Interface;
using System.Threading.Tasks;
using static CoreShop.Model.FromBody.DataResultModel;

namespace CoreShop.App
{
    public partial class FrmUser : UIForm
    {
        public bool returnValue;
        List<corecmsuser> lstSource = new List<corecmsuser>();
        OpaqueCommand cmd = new OpaqueCommand();
        public delegate void CloseFormPage(int pageIndex);
        public event CloseFormPage SetCloseFormPage;//新订单统计，frmMainWin.btn_NewBill
        public int mPageIndex = 0;
        public string number = "";
        private bool isSelect = false;
        public corecmsuser member_sel = null;
        public List<corecmsuser> _member_share = null;

        public FrmUser(string _number, bool _isSelect, List<corecmsuser> member_share = null)
        {
            number = _number;
            _member_share = member_share;
            isSelect = _isSelect;
            InitializeComponent();
        }
        public FrmUser()
        {
            InitializeComponent();
            this.ShowFullScreen = AppConstVars.showFullScreen;
        }

        #region 加载信息列表
        private async Task LoadDataListAsync(Int64 sTypeID, string str)
        {
            btnPg.PageSize = 20;
            cmd.ShowOpaqueLayer(pnl_Form, 125, true);
            try {
                MemberListResult memberListResult = await MemberApiUtil.GetMemberPage(str, mPageIndex, btnPg.PageSize);
                lstSource = memberListResult.data;
                btnPg.TotalCount = memberListResult.total;
                this.dgvMemberList.AutoGenerateColumns = false;
                this.dgvMemberList.DataSource = lstSource;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cmd.HideOpaqueLayer();
            }
        }
        #endregion
        private void LoadUserCategroy()
        {
            tv_usercategory.Nodes.Clear();
            List<corecmsusercategory> lstSource = new corecmsusercategoryServices().QueryAsync(0);
            TreeNode treeNode10 = new TreeNode("全部分类");
            treeNode10.Tag = "0";
            tv_usercategory.Nodes.Add(treeNode10);
            foreach (var item in lstSource)
            {
                TreeNode treeNode1 = new TreeNode(item.name);
                treeNode1.Tag = item.id.ToString();
                treeNode10.Nodes.Add(treeNode1);
            }
            tv_usercategory.Nodes[0].Expand();
        }
        private void FMember_Load(object sender, System.EventArgs e)
        {
            this.ShowFullScreen = AppConstVars.showFullScreen;
            if (!isSelect) btnSelect.Visible = false;
            mPageIndex = 1;
            LoadUserCategroy();
            _ = LoadDataListAsync(0, number);
        }

        private async void btnAddInfo_Click(object sender, System.EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isAddUserInfo, 0)) return;
            FrmUserRegister frmUserRegister = new FrmUserRegister("");
            //frm.Render();
            if (frmUserRegister.ShowDialog() == DialogResult.OK)
            {
                await LoadDataListAsync(0, txtSearch.Text.Trim());
            }
            frmUserRegister.Dispose();
            //FrmUserEdit frm = new FrmUserEdit(new corecmsuser());
            //frm.ShowDialog();
            //LoadDataList(0, txtSearch.Text.Trim());
            //frm.Dispose();
        }

        private void btnUpdate_Click(object sender, System.EventArgs e)
        {
            //if (dgvMemberList.SelectedRows.Count == 1)
            //{
            //    long MemberId = CommFunc.ConvertToInt64(dgvMemberList.SelectedRows[0].Cells["id"].Value);
            //    corecmsuser user = new corecmsuserServices().SelectUserById(MemberId);
            //    FrmUserEdit frm = new FrmUserEdit(user);
            //    frm.ShowDialog();
            //    LoadDataList(0, txtSearch.Text.Trim());
            //    frm.Dispose();
            //}
        }

        private async void btnSerach_Click(object sender, EventArgs e)
        {
            mPageIndex = 1;
            await LoadDataListAsync(0, txtSearch.Text.Trim());
        }

        private void dgvMemberList_CellDoubleClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            if (isSelect)
                btnSelect_Click(null, null);
            else
                btnUpdate_Click(null, null);
        }

        private async void btnAddType_Click(object sender, EventArgs e)
        {
            FrmUserCategoryEdit frm = new FrmUserCategoryEdit(new corecmsusercategory());
            //frm.Render();
            frm.ShowDialog();
            await LoadDataListAsync(0, txtSearch.Text.Trim());
            frm.Dispose();
        }

        private async void tv_usercategory_AfterSelect(object sender, TreeViewEventArgs e)
        {
            await LoadDataListAsync(CommFunc.ConvertToInt64(e.Node.Tag), "");
        }

        private async Task btnPg_PageChangedAsync(object sender, object pagingSource, int pageIndex, int count)
        {
            //List<corecmsuser> user = new List<corecmsuser>();
            //for (int i = (pageIndex - 1) * count; i < (pageIndex - 1) * count + count; i++)
            //{
            //    if (i >= lstSource.Count) continue;
            //    user.Add(lstSource[i]);
            //}
            //this.dgvMemberList.DataSource = user;
            mPageIndex = pageIndex;
            await LoadDataListAsync(0, txtSearch.Text.Trim());
        }

        private async Task btnRecharge_ClickAsync(object sender, EventArgs e)
        {
            try
            {
                if (dgvMemberList.SelectedRows.Count == 1)
                {
                    corecmsuser member = new corecmsuser();
                    long MemberId = CommFunc.ConvertToInt64(dgvMemberList.SelectedRows[0].Cells["id"].Value);
                    if (_member_share != null && _member_share.Count > 0)
                        member = _member_share.Find(p => p.id == MemberId);
                    else member = new corecmsuserServices().SelectUserById(MemberId);
                    new MemberUtil().SetUserDeposit(member);
                    await LoadDataListAsync(0, txtSearch.Text.Trim());
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void btnAccount_Click(object sender, EventArgs e)
        {
            var frm = new frmBalance();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void txtSearch_OkButtonClick(object sender, string value)
        {
            btnSerach_Click(null, null);
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            string sFileName = "";
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "选择一个文件";
            openFileDialog1.Multiselect = true;
            openFileDialog1.Filter = "Excel文件|*.xls|Excel文件|*.xlsx";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach (string fileName in openFileDialog1.FileNames)
                {
                    sFileName = fileName;
                }
            }

            if (string.IsNullOrEmpty(sFileName)) return;
            GetUseFromExcel(sFileName);
        }


        private void GetUseFromExcel(string toFileFullPath)
        {
            DataTable dt = new DataTable("Table_New");
            dt.Columns.Add("会员卡号", typeof(string));
            dt.Columns.Add("会员姓名", typeof(string));
            dt.Columns.Add("手机号", typeof(string));
            dt.Columns.Add("当前余额", typeof(decimal));
            dt.Columns.Add("当前赠送余额", typeof(decimal));
            dt.Columns.Add("当前积分", typeof(int));
            dt.Columns.Add("用户等级", typeof(string));
            dt.Columns.Add("折扣", typeof(int));
            FileStream fs = new FileStream(toFileFullPath, FileMode.Open);//打开myxls.xls文件
            HSSFWorkbook wk = new HSSFWorkbook(fs);   //把xls文件中的数据写入wk中
            for (int i = 0; i < wk.NumberOfSheets; i++)  //NumberOfSheets是myxls.xls中总共的表数
            {
                ISheet sheet = wk.GetSheetAt(i);   //读取当前表数据
                if (sheet.LastRowNum > 50000)
                {
                    UIMessageBox.Show("单次导入不能超过500条", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
                for (int j = 0; j <= sheet.LastRowNum; j++)  //LastRowNum 是当前表的总行数
                {
                    var row1 = sheet.GetRow(j);  //读取当前行数据
                    if ((row1 != null) && (j > 0))
                    {
                        DataRow dr = dt.NewRow();
                        dr["会员卡号"] = CommFunc.ConvertToString(row1.GetCell(0));
                        dr["会员姓名"] = CommFunc.ConvertToString(row1.GetCell(1));
                        dr["手机号"] = CommFunc.ConvertToString(row1.GetCell(2));
                        dr["当前余额"] = CommFunc.ConvertToDecimal(row1.GetCell(3));
                        dr["当前赠送余额"] = CommFunc.ConvertToDecimal(row1.GetCell(4));
                        dr["当前积分"] = CommFunc.ConvertToInt32(row1.GetCell(5));
                        dr["用户等级"] = CommFunc.ConvertToString(row1.GetCell(6));
                        dr["折扣"] = CommFunc.ConvertToInt32(row1.GetCell(7));
                        dr.EndEdit();
                        dt.Rows.Add(dr);
                    }
                }
            }
            if (!CheckExcelFile(dt)) return;
            dt = CheckExcelFileContent(dt);
            //var frm = new frmUserImport(dt);
            //frm.ShowDialog();
            //frm.Dispose();
        }

        private DataTable CheckExcelFileContent(DataTable dt)
        {
            //dt.Columns.Add("typeId", typeof(string));
            dt.Columns.Add("提示", typeof(string));
            //List<corecmsfoodcategory> typeList = new corecmsfoodcategoryServices().QueryAsync(0, "").ToList();
            bool checkRs = true;
            foreach (DataRow row in dt.Rows)
            {
                var strTip = string.Empty;
                // 获取当前行的目标列的值
                var number = row["会员卡号"].ToString();
                var mobile = row["手机号"].ToString();
                var discount = row["折扣"].ObjToDecimal();
                var gradeName = row["用户等级"].ToString();
                //List<corecmsfoodcategory> types = typeList.Where(p => p.name == type).ToList();
                // 检查值是否合格，这里使用了一个示例条件，你可以根据具体需要进行修改
                DataRow[] chekDiscountRow = dt.Select("折扣='" + discount + "'");
                DataRow[] chekNumberRow = dt.Select("会员卡号='" + number + "'");
                if (!string.IsNullOrEmpty(mobile))
                {
                    if (!CommonHelper.IsMobile(mobile))
                    {
                        strTip = "手机号码格式不正确";
                        checkRs = false;
                    }
                    else
                    {
                        DataRow[] checkMobileRow = dt.Select("手机号='" + mobile + "'");
                        if (checkMobileRow.Length > 1)
                        {
                            strTip = "存在相同手机号;";
                            checkRs = false;
                        }
                    }
                }

                DataRow[] chekGrade_DiscountRow = dt.Select("用户等级='" + gradeName + "' and   折扣<>" + discount + "");

                if (chekGrade_DiscountRow.Length >= 1)
                {
                    strTip = "同一用户等级不能设置不同折扣;";
                    checkRs = false;
                }


                if (discount <= 0 || discount > 100)
                {
                    strTip = "折扣应该在大于0并且小于等于100;";
                    checkRs = false;
                }

                if (chekNumberRow.Length > 1)
                {
                    strTip = "存在相同会员卡号;";
                    checkRs = false;
                }

                row["提示"] = strTip;
            }
            return dt;
        }


        private bool CheckExcelFile(DataTable dt)
        {
            if (dt.Columns.Contains("会员卡号") == false)
            {
                UIMessageBox.Show("【会员卡号】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("会员姓名") == false)
            {
                UIMessageBox.Show("【会员姓名】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("手机号") == false)
            {
                UIMessageBox.Show("【手机号】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("当前余额") == false)
            {
                UIMessageBox.Show("【当前余额】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("当前赠送余额") == false)
            {
                UIMessageBox.Show("【当前赠送余额】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("当前积分") == false)
            {
                UIMessageBox.Show("【当前积分】的列不存在，无法导入。");
                return false;
            }
            if (dt.Columns.Contains("用户等级") == false)
            {
                UIMessageBox.Show("【用户等级】的列不存在，无法导入。");
                return false;
            }

            if (dt.Columns.Contains("折扣") == false)
            {
                UIMessageBox.Show("【折扣】的列不存在，无法导入。");
                return false;
            }

            return true;
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (dgvMemberList.SelectedRows.Count == 1)
            {
                long MemberId = CommFunc.ConvertToInt64(dgvMemberList.SelectedRows[0].Cells["id"].Value);
                if (_member_share != null && _member_share.Count > 0)
                    member_sel = _member_share.Find(p => p.id == MemberId);
                else member_sel = new corecmsuserServices().SelectUserById(MemberId);
                if (member_sel == null)
                {
                    UIMessageBox.Show("选择的会员不存在。");
                    return;
                }
                this.DialogResult = DialogResult.Yes;
            }
        }

        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13) btnSerach_Click(null,null);
        }

        public async void btnPg_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            mPageIndex = pageIndex;
            await LoadDataListAsync(0, txtSearch.Text.Trim());
        }

        private async void ubtPoint_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvMemberList.SelectedRows.Count == 1)
                {
                    long MemberId = CommFunc.ConvertToInt64(dgvMemberList.SelectedRows[0].Cells["id"].Value);
                    corecmsuser member = new corecmsuserServices().SelectUserById(MemberId);
                    if (_member_share != null && _member_share.Count > 0)
                        member = _member_share.Find(p => p.id == MemberId);
                    else member = new corecmsuserServices().SelectUserById(MemberId);
                    if ((member == null) || (member.id == 0))
                    {
                        MessageBox.Show("没有选择会员。");
                        return;
                    }
                    new MemberUtil().SetUserPoint(member);
                    await LoadDataListAsync(0, txtSearch.Text.Trim());
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}